<template>
  <Head />
  <Bread :title="$t('menu2')" />
  <main class="container">
    <div class="content">
      <van-form @submit="onSubmit" class="form">
        <van-cell-group inset>
          <van-field :style="{ margin: 0 }" v-model="amount" :placeholder="$t('pleaseEnter')" />
        </van-cell-group>
        <div class="submit">
          <van-button :disabled="!userinfo" class="btn" @click="onSubmit" :loading="loading" :loading-text="$t('pledge')">
            {{ !userinfo ? $t("pleaseRegister") : $t("pledge") }}
          </van-button>
        </div>
      
      </van-form>

      <p>（<van-icon name="fail" />{{ $t("ntfTips") }}）</p>
    </div>
    
    <van-checkbox-group v-model="checked" ref="checkboxGroup" checked-color="#ffe07b">

    <div class="grid-container">
        
      <div class="grid-item" v-for="(item, index) in nftList" :key="index">
       
        <img :src="item.url" alt="" />
        <div class="bottom">
          <p>#{{ item.token }} ${{ item.nftTotalMoney }}</p>

          <!-- <van-button v-if="item.hasRedemption == 2" class="redemptionBtn" @click="onRedemption(item)"
            :loading="timeLoading" :loading-text="$t('pledge')">
            {{ $t("redemption") }}
          </van-button>
          <span class="down-time" v-if="item.hasRedemption == 3">
            <img src="@/assets/images/time.png" alt="" />
            {{ item.showTime }}
          </span> -->
          <van-checkbox :name="item.code">
          </van-checkbox>
        </div>
     
      </div>


    </div>
  </van-checkbox-group>
  <van-floating-bubble icon="cluster" color="#ffe07b" @click="craft" v-if="checked.length>2 && showMerge" />

  </main>
</template>
<script setup lang="ts">

import { Async_nfts, Async_redemption,Async_craft } from "@/server/user";
import { showToast, showConfirmDialog } from "vant";
import { useI18n } from "vue-i18n";
import { Contract } from "@/utils/wallet/contract";
import { formatTime } from "@/utils/tool";
import { userStore } from '@/stores/modules/user'


const { t } = useI18n();
const amount = ref("");
const loading = ref(false);
const timeLoading = ref(false);
const baseURL = "//btwgswap.github.io/nft/pizzaspace/images/";
const baseNewURL = "//btwgswap.github.io/nft/pizzaspaceclub/images/";

const nftList = ref([]);
const nftMap = ref(Map);
const userinfo = userStore().info;
const checked = ref([]);
const checkboxGroup = ref(null);

    

    const showMerge=computed(()=>{
     var totalAmount =0
      checked.value.forEach((item)=>{
        totalAmount+= nftMap[item].nftTotalMoney
      })
      return  totalAmount%600==0
    })

const getList = async () => {
  try {
    let { list }: any = await Async_nfts({
      page: 0,
      size: 999,
    });
    if (list) {
      nftList.value = list || [];
      nftList.value.forEach((item) => {
        nftMap[item.code]=item
        
        if (item.level > 0){
          item.url = baseNewURL+ (item.token % 5) + ".jpg";
        }else{
          item.url = baseURL + (item.token % 10) + ".jpg";
        }
        if (item.hasRedemption == 3) {
          isTimestampWithin7Days(item.redemptionAt, item);
        }
      });
    }
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  getList();
  loading.value = false;
});

const onSubmit = async () => {
  if (!amount.value) {
    return showToast(t("pleaseDonationNum"));
  }
  loading.value = true;
  Contract.pledgeNFT(amount.value.split(","))
    .then((res: any) => {
      loading.value = false;

      if (res && res.type == "approve") {
        showToast(t("successApprove"));
        return;
      }
      showToast(t("successOperation"));
      getList();
    })
    .catch((err) => {
      loading.value = false;
      console.log(err);
      showToast(t("pledgeErr"));
    });
};

const onRedemption = ({ code }) => {
  showConfirmDialog({
    title: t('prompt'),
    message: t('confirmRedemption'),
    cancelButtonColor:"#000"
  }).then(async () => {
    try {
      timeLoading.value = true;
      await Async_redemption({ code: String(code) });
      timeLoading.value = false;
      showToast(t("successOperation"));
      getList();
    } catch (error) {
      console.error(error);
    } finally {
      timeLoading.value = false;
    }
  });
};


const craft = () => {
  showConfirmDialog({
    title: t('prompt'),
    message: t('confirmNftMerge'),
    cancelButtonColor:"#000"
  }).then(async () => {
    try {
      timeLoading.value = true;
      await Async_craft(checked.value);
      timeLoading.value = false;
      showToast(t("successOperation"));
      getList();
    } catch (error) {
      console.error(error);
    } finally {
      timeLoading.value = false;
    }
  });
};

const isTimestampWithin7Days = (givenTimestamp, item) => {
  // 获取当前时间戳
  const currentTimestamp = Math.floor(Date.now() / 1000);
  // 计算剩余秒数 = 给定的时间戳 - 当前系统时间戳
  let seconds = givenTimestamp - currentTimestamp;
  var interval = setInterval(() => {
    seconds--;
    if (seconds < 0) {
      item.showTime = "0天 00:00:00";
      clearInterval(interval);
    } else {
      item.showTime = formatTime(seconds);
    }
  }, 1000);
};
</script>
<style scoped lang="scss">
.container {
  padding: 12px;

  .content {
    padding: 12px;
    background: linear-gradient(rgba(25, 31, 50, 0.2), rgb(4 8 20 / 0.01)),
      rgb(4 8 20 / 0.8);
    box-shadow: inset 0 0 0 1px rgb(200 200 220 / 0.16), inset 0 0 5px -3px #0f2bff,
      inset 0 12px 48px 0 rgb(160 220 240 / 0.08), inset 0 0 120px -100px #0f2bff;
    border-radius: 10px;
    margin-bottom: 12px;
  }

  .form {
    padding-bottom: 10px;

    .submit {
      width: 100%;
      padding: 10px 0;
      display: flex;
      align-items: center;

      .btn {
        width: 100%;
        height: 42px;
        background: linear-gradient(to right, #ffe07b, #e8a22d);
        font-size: 15px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #ffffff;
        border-radius: 20px;
        letter-spacing: 5px;
      }
    }
  }

  p {
    font-size: 12px;
    color: #aacccc;
  }
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  width: 100%;
  box-sizing: border-box;
}

.grid-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-radius: 6px;
  object-fit: cover;
  background: linear-gradient(rgba(25, 31, 50, 0.2), rgb(4 8 20 / 0.01)),
    rgb(4 8 20 / 0.8);
  box-shadow: inset 0 0 0 1px rgb(200 200 220 / 0.16), inset 0 0 5px -3px #0f2bff,
    inset 0 12px 48px 0 rgb(160 220 240 / 0.08), inset 0 0 120px -100px #0f2bff;

  img {
    object-fit: cover;
    border-radius: 6px;
    height: 200px;
  }

  .bottom {
    // border-top: 1px solid #fff;
    border-top: 1px solid rgba(42, 52, 96, 0.5);
    width: 100%;
    box-sizing: border-box;
    padding: 10px 0 10px 0;
    display: flex;
    flex-direction: column;
    align-items: center;

    p {
      font-size: 14px;
      color: #fff;
      font-weight: bold;
      text-align: center;
      line-height: 14px;
      margin-bottom: 5px;
    }

    .redemptionBtn {
      width: 70%;
      padding: 10px;
      background: linear-gradient(to right, #ffe07b, #e8a22d);
      line-height: 15px;
      font-size: 15px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #ffffff;
      border-radius: 20px;
    }

    .down-time {
      display: flex;
      align-items: center;
      color: #fff;

      img {
        height: 15px;
        margin-right: 5px;
      }
    }
  }
}

::v-deep .van-cell-group--inset {
  margin: 0;
}
::v-deep .van-floating-bubble{
  background: #e8a22d;
}
</style>
